#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: repo-apply.sh
# Description: 
#     Due to limitation of the google repo tool you need to manually apply a repo patch to the repo repository when porting android to other platforms. 
#     This script automates this process.
#     Use this script to automatically split the repo patch file in individual patch files and automatically apply them to the individual git repositories 
#	  inside the repo repository. Usage: repo-apply The script will take the patch file and split the file into individual patch files for each git repository. 
# 	  Then the script will apply each individual patch file to the correct git repository using 'git apply'.
#   
# Edit History: 
#   2010-11-30    File created.
#========================================================================


# script to apply a patchfile to a repo repository
# author: lynx
# email: gizmo@neuronetix.de

if [ $# -ne 2 ]; then
echo "Usage: $(basename $0) <repoPatchFile> <repoPath>"
exit 1
fi

sPatchFile="$1"
sRepoPath="$2"

mkdir /tmp/.patches

nCnt=$(grep -c ^project $1)
nCnt=$(($nCnt - 1))
csplit -f /tmp/.patches/patch. $sPatchFile /^project/ {$nCnt}
for sPatch in /tmp/.patches/patch.*; do
    sPatchPath="$(cat $sPatch | grep "project" | grep -v grep)"
        if [ -n "$sPatchPath" ]; then
            sPatchPath="$(echo $sPatchPath | awk {'print $2'})"
        pushd "$sRepoPath/$sPatchPath"
                echo "Patching $sPatch in $sRepoPath/$sPatchPath"
        git apply --reject --whitespace=fix $sPatch
        echo "Patch End $sPatch"
                popd
        fi
    done

rm -rf /tmp/.patches
exit 0
